// 找参考资料结果
import { analyzeData } from '@/services/ant-design-pro/highClassWrite.ts';
import { replaceN } from '@/utils/index';
import { message, Modal } from 'antd';
import { nanoid } from 'nanoid';
import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import DropDownSelect from './DropDownSelect';
import { AnalyzeIcon, MarkersIcon } from './svg.js';
const MarkerProfile: React.FC<any> = ({
  data,
  scrollToBottom,
  onComplete = () => {},
  triggerReference,
  triggerArticleMain,
  setAILogs,
  dispatch,
}) => {
  const [list, setList] = useState([]);
  const [isDemoOpen, setIsDemoOpen] = useState(false);
  const [currentDemo, setCurrentDemo] = useState(null); //当前示例

  //公共更新model的方法
  const updateState = (updateObj: any) => {
    dispatch({
      type: 'highClassWrite/updateState',
      payload: updateObj,
    });
  };
  const splitContent = (content: any, limit = 300) => {
    const truncatedContent = content.slice(0, limit);
    // 使用换行符 '\n' 分割截取后的文本
    const paragraphs = truncatedContent.split('\n').filter((p) => p.trim() !== ''); // 过滤掉空段落
    // 只包装前三个段落
    const firstThreeParagraphs = paragraphs.slice(0, 3);
    // 使用 map 函数将段落包装在 <p> 标签中
    const formattedContent = firstThreeParagraphs
      .map((p: any, index: number) => {
        if (index === firstThreeParagraphs.length - 1) {
          // 最后一个段落添加 class="ptwo"
          return `<p class="ptwo">${p}</p>`;
        }
        return `<p>${p}</p>`;
      })
      .join(''); // 将包装后的文本段落拼接成一个字符串

    return formattedContent;
  };
  useEffect(() => {
    if (data && data.length > 0) {
      //处理数据
      let ls: any = [];
      data.forEach((item: any) => {
        let newObj = {
          key: nanoid(),
          source: item.source,
          subject: item.subject,
          detail: item.detail,
          main_body: item.main_body,
          content: splitContent(item.main_body),
        };
        ls.push(newObj);
      });
      // setList(ls);
      // 使用 setTimeout 逐个添加数据
      const addDataWithDelay = (index: number) => {
        if (index < ls.length) {
          setTimeout(() => {
            setList((prevList) => [...prevList, ls[index]]);
            addDataWithDelay(index + 1); // 递归调用以添加下一条数据
            scrollToBottom('', 6);
          }, 800); // 间隔一秒添加一条数据
        } else if (index === ls.length) {
          if (typeof onComplete === 'function') {
            onComplete(false); //如果外部有传入 执行
          }
        }
      };
      // 启动添加数据的过程
      addDataWithDelay(0);
    }
  }, [data]);

  const lookSource = (data: any) => {
    setIsDemoOpen(true);
    setCurrentDemo(data);
  };
  //关闭示例
  const demoModalCancel = () => {
    setIsDemoOpen(false);
  };
  //点击分析
  const handleAnalyze = async (item: any) => {
    updateState({
      robotLoading: true,
    });
    //添加文件参考方向选择框
    let systemTxtRecover = {
      key: nanoid(),
      type: 'systemTxtRecover',
      spend: 30,
      data: [`好的，小麦正在分析资料`],
    };
    setAILogs((prev: any) => [...prev, systemTxtRecover]);

    scrollToBottom();
    let body = {
      subject: item.subject,
      main_body: item.main_body,
      material_type: '内容资料',
    };
    let res = await analyzeData(body);
    if (res.code === 0) {
      //添加文件参考方向选择框
      let analyzeResult = {
        key: nanoid(),
        type: 'analyzeResult',
        data: [
          {
            subject: res?.data?.subject,
            main_body: res?.data?.result,
          },
        ],
      };
      setAILogs((prev) => [...prev, analyzeResult]);
    } else {
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
    updateState({
      robotLoading: false,
    });
  };

  return (
    <>
      {list.length > 0 &&
        list.map((item) => (
          <div className="findInfoBox" key={nanoid()}>
            <div className="sourceBox ">
              <div
                className="sourceTopBox"
                dangerouslySetInnerHTML={{
                  __html: item?.content,
                }}
              ></div>
              <div className="sourceBottomBox">
                <div className="sourceBottomBox-hd">{item.source}</div>
                {/* {item?.main_body?.length > 50 && ( */}
                <div
                  className="sourceBottomBox-bd"
                  onClick={() => {
                    lookSource(item);
                  }}
                >
                  查看原文
                </div>
                {/* )} */}
              </div>
            </div>
            <div className="findInfoHandleBox">
              <span className="iconBox" onClick={() => handleAnalyze(item)}>
                <MarkersIcon />
              </span>
              <DropDownSelect
                item={item}
                triggerReference={triggerReference}
                triggerArticleMain={triggerArticleMain}
                setAILogs={setAILogs}
              >
                <span className="iconBox">
                  <AnalyzeIcon />
                </span>
              </DropDownSelect>
            </div>
          </div>
        ))}
      <Modal
        centered
        className="articleSourceModal"
        title={currentDemo?.subject || ' '}
        open={isDemoOpen}
        footer={null}
        onCancel={demoModalCancel}
        width={650}
      >
        <div dangerouslySetInnerHTML={{ __html: replaceN(currentDemo?.main_body) }}></div>
      </Modal>
    </>
  );
};

// export default MarkerProfile;
export default connect(({ highClassWrite }) => ({ highClassWrite }))(MarkerProfile);
